﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ClassLibrary.Entity;
using ClassLibrary.DAO;
using ClassLibrary.Utilities;

public partial class Client_UserControl_ucChangePass : System.Web.UI.UserControl
{
    TblAccountsDAO userDAO = new TblAccountsDAO(Global.CONNECTION_STRING);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Login();
    }
    private void Login()
    {
        try
        {
            if (Session[Global.SESSION_LOGGED_USER] == null)
            {
                btnSubmit.Enabled = false;
                lblMessage.Text = "Đăng nhập !";
                return;
            }

            txtEmail.Text = ((TblAccounts)Session[Global.SESSION_LOGGED_USER]).EmailAcc;
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE);
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        EmailService emailSrv = new EmailService();
        bool bFlag = false;
        try
        {
            if (Session[Global.SESSION_LOGGED_USER] == null)
            {
                return;
            }
            TblAccounts user = (TblAccounts)Session[Global.SESSION_LOGGED_USER];

            if (userDAO.GetUser(txtEmail.Text, Encryption.EncryptToString(txtOldPass.Text)) == null)
            {
                lblMessage.Text = "Invalid Password";
                txtOldPass.Text = txtPassword.Text = txtRePassword.Text = "";
                return;
            }
            user.PasswordAcc = Encryption.EncryptToString(txtPassword.Text);
            userDAO.InsUpdAccounts(user, 3);

            //send mail
            emailSrv.SendChangePasswordEmail(user, Server.MapPath(Global.CHANGE_PASSWORD), txtPassword.Text);


            bFlag = true;

        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE);
        }
        if (bFlag)
        {
            lblMessage.Text = "Password changed successfully";
            txtOldPass.Text = txtPassword.Text = txtRePassword.Text = "";
        }
    }
}
